package cn.com.bsfit.netty.handler;

import cn.com.bsfit.netty.business.BusinessService;
import cn.com.bsfit.netty.req.ReqData2MapFacade;
import com.google.common.base.Stopwatch;
import cn.com.bsfit.netty.config.properties.BaseNettyServerProperties;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 类名 SocketRequestHandler
 * 描述 TODO
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/9/29 16:55
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "netty.server", name = "enable" ,havingValue = "true")
public class SocketRequestHandler extends AbstractRequestHandler<BaseNettyServerProperties> {
    private static final long serialVersionUID = 5106143657009716158L;

    @Autowired
    private BaseNettyServerProperties nettyServerProperties;

    @Override
    public BaseNettyServerProperties getNettyServerProperties() {
        return nettyServerProperties;
    }

    @Autowired(required = false)
    private BusinessService businessService;

    @Override
    public Map<String, Object> reqHandler(Map<String, Object> reqMap, ReqData2MapFacade reqData2MapFacade) throws Exception {
        if (businessService == null){
            throw new RuntimeException("请先实现BusinessService接口并申明为Bean");
        }
        return businessService.reqHandler(reqMap, reqData2MapFacade);
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush().close().sync();
    }

    @Override
    protected void writeResponse(ChannelHandlerContext ctx, String resultMsg, Stopwatch stopwatch) {
        ByteBuf buf = Unpooled.copiedBuffer(resultMsg, CharsetUtil.UTF_8);
        stopwatch.stop();
        log.info("call socket cost times : {}", stopwatch);
        ctx.writeAndFlush(buf);
    }

    @Override
    protected Map<String, Object> getBaseResponseError(String errMsg) {
        return businessService.getBaseResponseError(errMsg);
    }
}
